package lion.web.interceptors.rewrite;

import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang.StringUtils;

/**
 * use the rules defined in linkrewrite.xml to replace urls from a html text
 *
 * @author lion
 * @mail hl_0074@sina.com
 * @date 2011-10-12
 */
public class LinkURLRewriter {

	private static Pattern URLPattern = Pattern.compile("(href|src|action|value|file)\\s*=['\"](.*?)['\"]");

	private LinkURLRewriter() {

	}

	public static String rewrite(String html) {

		return rewrite(html, RewriteConf.getRewriteRules());
	}

	public static String rewrite(String html, List<RewriteRule> rewriteRules) {

		if (StringUtils.isBlank(html)) { return ""; }
		if (!RewriteConf.isEnabled()) { return html; }

		Matcher m = URLPattern.matcher(html);
		StringBuffer sbu = new StringBuffer();
		while (m.find()) {
			String url = m.group(2);
			boolean find = false;
			for (RewriteRule rewriteRule : rewriteRules) {
				String tmp = rewriteRule.rewrite(url);
				if (tmp != null) {
					url = tmp;
					find = true;
					if (rewriteRule.isLast()) {
						break;
					}
				}
			}
			if (find) {
				m.appendReplacement(sbu, "$1=\"" + url + "\"");
			}
		}
		m.appendTail(sbu);
		return sbu.toString();
	}
}
